<?php

namespace control;

class outStockExecClass extends adIndexClass
{
    private const power = 'outStockExec';
    private const printPage = 'outStock';
    private const page = 'outStockExec';
    private const table = 'inventory_changes';
    private const tableMx = 'inventory_changes_detail';
    private const tableRecord = 'inventory_record';
    private const title = '出库单';
    private const source = ['生产领料', '销售发货', '采购退货', '配料出库', '委外退货', '委外领料', '其他出库'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {

        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.outStockExec.homeListSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => '{l.outStockExec.homeListSearch.type}',
                        'width' => 200,
                    ],
                    'target'  => [
                        'name'  => '{l.outStockExec.homeListSearch.target}',
                        'width' => 300,

                    ],
                    'confirmTime'  => [
                        'name'  => '{l.outStockExec.homeListSearch.confirmTime}',
                        'width' => 280,
                        'sort' => 1,
                    ],
                    'text'  => [
                        'name'  => '{l.outStockExec.edit.text}',
                        'width' => 300,
                    ],
                    'state'         => [
                        'name'  => '{l.outStockExec.homeListSearch.state}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('outStockExec.homeList.type') => select(["name" => "type", 'option' => self::source]),
                    L('outStockExec.homeList.orderNo')   => text(array("name" => "orderNo")),
                    L('outStockExec.homeList.sourceTargetName')   => text(array("name" => "sourceTargetName")),
                ],
                [
                    '出库完成日期'  => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . static::page;
        if ($this->power(static::power, "edit")) {
            $button .= "<span onclick=\"newIframe('" . static::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>" . L('outStockExec.homeListSearch.newOutStock') . "</span>\n";
        }
        if ($this->power(static::power, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('outStockExec.homeListSearch.del') . "</span>\n";
        }
        if ($this->power(self::power, "cancel")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'cancel'})\">" . L('inStockExec.homeListSearch.cancel') . "</span>\n";
        }
        if ($this->power(static::power, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>" . L('outStockExec.homeListSearch.batchPrint') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(static::power, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if (para('CSAIII') == '是') {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'updateTime'})\">修改完成时间</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //查询结果
        $where = " coid = '" . static::$coid . "' AND classify = 0 ";
        $equal = [
            'type' => $this->post('type'),
        ];
        $like  = [
            'orderNo'          => $this->post('orderNo'),
            'sourceTargetName' => $this->post('sourceTargetName'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= static::timeComparison($this->post('orderDate'), 'date', 'confirmTime');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'CASE WHEN confirmTime IS NULL THEN 0 ELSE 1 END,CASE WHEN confirmTime IS NULL THEN time ELSE NULL END DESC,confirmTime',//  -- 将confirmTime为NULL的放在前面  -- confirmTime为NULL的情况下按照time倒序  -- 最后按照confirmTime倒序
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                          = $this->page(array(
            "table" => static::table,
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[static::page]['sql'] = $page['sql'];
        $isPrint                       = $this->power(self::power, "print");
        $checkCtrl                     = optionSettingClass::getSettingItem('库存', 'checkCtrl');// 库存是否需要复核
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . static::page;
        foreach ($page['array'] as $array) {
            $edit = ($array['state'] == '待出库' || ($array['state'] == '已出库' && $checkCtrl));
            //列表控件
            $dominate = [
                "box"    => ["name" => "listId", "value" => $array['id'],],
                "detail" => ["title" => L('outStockExec.homeListSearch.detail'), "click" => "newIframe('" . L('outStockExec.homeListSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')",],
                "edit"   => $edit ? ["title" => L('outStockExec.homeListSearch.edit'), "click" => "newIframe('" . L('outStockExec.homeListSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')",] : [],
                'print'  => ($isPrint === true) ? ['title' => L('outStockExec.homeListSearch.print'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . static::page . "&fun=printPage&id={$array['id']}')"] : [],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'target':
                        $target   = static::getCompanyName($array['targetId']);
                        $row[] = $target;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::power, 'import')) {
            $_SESSION['warn'] = L('outStockExec.importData.power');
        }  else {
            $exampleData[] = [
                '', '销售发货', 'C001', 'A客户', '样例数据', '', 'YL002', 'B原料', 'CK001', 'A产品仓库', 'P0001', '默认仓位', 100, 50, '', '2023-03-16',
            ];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '单据编号'=>$example[0],
                            '业务类型'=>$example[1],
                            '往来单位编号'=>$example[2],
                            '往来单位名称'=>$example[3],
                            '单据备注'=>$example[4],
                            '待出库单号'=>$example[5],
                            '物料编码'=>$example[6],
                            '物料名称'=>$example[7],
                            '仓库编码'=>$example[8],
                            '仓库名称'=>$example[9],
                            '库位编码'=>$example[10],
                            '库位名称'=>$example[11],
                            '数量'=>$example[12],
                            '单价'=>$example[13],
                            '批次'=>$example[14],
                            '单据日期'=>$example[15],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text   = str_replace(["{{staffName}}"], [$this->control['name']], L('outStockExec.importData.importTempLog'));
            $this->logText(["type" => self::power, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::power, 'import')) {
            $json['warn'] = L('outStockExec.importData.power');
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x         = 0;
            $text      = '';
            $saleOrder = [];
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    if (!empty($cell['业务类型'])) {
                        $saleOrder   = [];
                        $companyInfo = query('kehu', "orderNo = '$cell[往来单位编号]' and coid = '" . self::$coid . "' ", " khid as id,concat(orderNo,'-',companyName) as name ");
                        if (empty($companyInfo['id'])) {
                            $companyInfo = query('supplier', "code = '$cell[往来单位编号]' and coid = '" . self::$coid . "'", " id,concat(code,'-',name) as name ");
                        }
                        $field      = [
                            'type'       => $cell['业务类型'],
                            'targetId'   => $companyInfo['id'],
                            'recordDate' => self::importDateFormat($cell[16]),
                            'text'       => $cell['单据备注'],
                        ];
                        $annotation = [
                            'type'     => L('outStockExec.editEdit.type'),
                            'targetId' => L('outStockExec.editEdit.targetId'),
                            'text'     => L('outStockExec.editEdit.text'),
                        ];
                        $rules      = [
                            'type' => 'required',
                        ];
                        $info       = query(self::table, "classify = 0 and orderNo = '$cell[单据编号]' and coid = '" . self::$coid . "'");
                        // 校验是否符合规则
                        $vt     = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                        } elseif (!in_array($field['type'], self::source)) {
                            $text .= "\n第【{$row_list}】行，" . L('outStockExec.editEdit.importWarnOne');
                        } elseif (!empty($info['id']) && $info['state'] != '待出库') {
                            $text .= "\n第【{$row_list}】行，" . L('outStockExec.editEdit.importWarnTwo');
                        } else {
                            if (empty($info['id'])) {
                                // 新增
                                $userNo = codeTemplateClass::generateCode(static::power, [
                                    'prefix' => 'CKD' . date('Ymd', strtotime($field['recordDate'])),
                                    'table'  => static::table,
                                    'field'  => 'orderNo',
                                    'where'  => " AND coid = '" . static::$coid . "' ",
                                ], $field);
                                $field  = array_merge($field, [
                                    'id'               => suiji(),
                                    'orderNo'          => $userNo,
                                    'classify'         => 0,
                                    'sourceTargetName' => $companyInfo['name'],
                                    'state'            => '待出库',
                                    'coid'             => self::$coid,
                                    'stid'             => $this->control['stid'],
                                    'time'             => $field['recordDate'] ?: $this->time,
                                ]);
                                $warn   = static::insert([
                                    "table" => self::table,
                                    "field" => $field,
                                ]);
                            } else {
                                $warn = static::update([
                                    "table" => self::table,
                                    "field" => $field,
                                    'where' => "id = '$info[id]'",
                                ]);
                            }
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $saleOrder = match ($warn) {
                                    '新增成功' => $field,
                                    default => $info
                                };
                            } else {
                                $text .= "\n第【{$row_list}】行，编辑主数据失败，" . $warn;
                            }
                        }
                    }
                    if (isset($saleOrder['id']) && !empty($saleOrder['id'])) {
                        $material  = query('material', "coid = '" . self::$coid . "' and code = '$cell[物料编码]'");
                        $warehouse = query('warehouse', "orderNo = '$cell[仓库编码]' and coid = '" . self::$coid . "'");
                        if (empty($material['id'])) {
                            $text .= "\n第【{$row_list}】行，物料不存在";
                            continue;
                        } elseif (empty($warehouse['id'])) {
                            $text .= "\n第【{$row_list}】行，仓库不存在";
                            continue;
                        }
                        //库位匹配
                        if ($cell['库位编码']) {
                            $positionId = query("warehouse_position", " orderId = '" . $warehouse['id'] . "' and code = '$cell[库位编码]' ", "id")['id'];
                        } else {
                            $positionId = inventoryBalanceClass::matchLocation($warehouse['id']);
                        }
                        if (empty($positionId)) {
                            $text .= "\n第【{$row_list}】行，库位不存在或默认库位不存在";
                            continue;
                        }
                        $mx        = query(self::tableMx, "materialId = '$material[id]' and orderId = '$saleOrder[id]' and sourceNo = '$cell[待出库单号]' and batch = '$cell[批次]'");
                        $cell['数量']  = self::formattingFigure($cell['数量'], 'numPrecision');
                        $price     = $cell['单价'] ? self::formattingFigure($cell['单价'], 'pricePrecision') : $material['buyPrice'];
                        $orderNum  = 0;
                        $sourceNo  = "";
                        $inventory = query('inventory', "coid = '" . self::$coid . "' and orderNo = '$cell[待出库单号]'");
                        if (!empty($inventory['id'])) {
                            $inventory_detail = query('inventory_detail', "orderId = '$inventory[id]' and materialId = '$material[id]'");
                            $orderNum         = $inventory_detail['orderNum'];
                            $sourceNo         = $inventory['orderNo'];
                            $price            = inventoryBalanceClass::unitPrice($material['id']);
                        }
                        if (empty($mx['id'])) {
                            //明细
                            $mxField = [
                                'id'          => suiji(),
                                'coid'        => self::$coid,
                                'orderId'     => $saleOrder['id'],
                                'materialId'  => $material['id'],
                                'orderNum'    => $orderNum,
                                'batch'       => $cell['批次'],
                                'num'         => $cell['数量'],
                                'unit'        => $inventory_detail['unit'] ?? $material['unit'],
                                'price'       => $price,
                                'money'       => self::formattingFigure($price * $cell['数量']),
                                'warehouseId' => $warehouse['id'],
                                'positionId'  => $positionId,
                                'sourceTable' => isset($inventory_detail['id']) ? 'inventory_detail' : '',
                                'sourceId'    => $inventory_detail['id'] ?? '',
                                'sourceNo'    => $sourceNo,
                            ];
                            $warn    = static::insert([
                                "table" => self::tableMx,
                                "field" => $mxField,
                            ]);
                        } else {
                            //明细
                            $mxField = [
                                'materialId'  => $material['id'],
                                'orderNum'    => $orderNum,
                                'batch'       => $cell['批次'],
                                'num'         => $cell['数量'],
                                'unit'        => $inventory_detail['unit'] ?? $material['unit'],
                                'price'       => $price,
                                'money'       => self::formattingFigure($price * $cell['数量']),
                                'warehouseId' => $warehouse['id'],
                                'positionId'  => $positionId,
                                'sourceTable' => isset($inventory_detail['id']) ? 'inventory_detail' : '',
                                'sourceId'    => $inventory_detail['id'] ?? '',
                                'sourceNo'    => $sourceNo,
                            ];
                            $warn    = static::update([
                                "table" => self::tableMx,
                                "field" => $mxField,
                                'where' => "id = '$mx[id]'",
                            ]);
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $text .= "\n第【{$row_list}】行，导入成功";
                            $x++;
                        } else {
                            $text .= "\n第【{$row_list}】行，导入失败：插入数据库失败，" . $warn;
                        }
                    } else {
                        $text .= "\n第【{$row_list}】行，未找到单据";
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::power, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(static::power, 'export')) {
            $_SESSION['warn'] = L('outStockExec.exportData.power');
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by CASE WHEN confirmTime IS NULL THEN 0 ELSE 1 END,CASE WHEN confirmTime IS NULL THEN time ELSE NULL END DESC,confirmTime desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $target = static::getCompanyName($array['targetId']);
                $mx     = find(array('table' => static::tableMx, 'where' => "orderId = '$array[id]' order by list"));
                foreach ($mx['array'] as $value) {
                    $material = query('material', " id = '$value[materialId]'");
                    if ($value['sourceId']) {
                        $putOut = find(array('table' => static::tableRecord, 'single' => "inventoryMxId = '$value[sourceId]'", 'field' => " IFNULL(sum(num),0)*-1 as num "));
                    } else {
                        $putOut['num'] = 0;
                    }
                    $price          = self::lostZero($value['price'], 'pricePrecision');
                    $batchInventory = inventoryBalanceClass::inventoryNum($material['id'], $value['warehouseId'], $value['positionId'], $value['batch']);
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '单据编号' => $array['orderNo'],
                                '业务类型' => $array['type'],
                                '往来单位' => $target,
                                '入库完成时间' => $array['confirmTime'],
                                '状态' => $array['state'],
                                '待入库单号' => $value['sourceNo'],
                                '物料编码' => $material['code'],
                                '物料名称' => $material['name'],
                                '规格型号' =>  $material['model'],
                                '单位' => $value['unit'],
                                '仓库' =>  warehouseClass::getName($value['warehouseId']),
                                '库位' =>warehousePositionClass::getName($value['positionId']),
                                '单据数量' => self::lostZero($value['orderNum'], 'numPrecision'),
                                '已出库数量'=>  static::lostZero($putOut['num'], 'numPrecision'),
                                '本次出库数量'=>  static::lostZero($value['num'], 'numPrecision'),
                                '装箱数'=> static::lostZero($value['packing_quantity'], 'numPrecision'),
                                '箱容数'=> static::lostZero($value['box_capacity'], 'numPrecision'),
                                '余数'=>static::lostZero($value['remainder'], 'numPrecision'),
                                '批号'=> $value['batch'],
                                '单价'=>$price,
                                '批次可用数量'=>$batchInventory,
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }

            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('outStockExec.exportData.log'));
            $this->logText(["type" => static::power, "text" => $text]);
            $this->excelOut($title, $data, L('outStockExec.exportData.fileName') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id');
        $info     = query(static::table, " coid = '" . static::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => L('outStockExec.edit.save'),
            "type"  => "点击事件",
            "title" => L('outStockExec.edit.save'),
            'fun'   => "subForm('" . static::page . "EditForm','" . root . "control/adIndex.html?cla=" . static::page . "&fun=editEdit')",
        ];
        $tr[]     = ['{l.outStockExec.edit.operate}', '{l.outStockExec.edit.sourceNo}', '{l.outStockExec.edit.code}', '{l.outStockExec.edit.name}', '{l.outStockExec.edit.model}', '{l.outStockExec.edit.unit}', '{l.outStockExec.edit.orderNum}', '{l.outStockExec.edit.num}', '<div class="warehouse">' . '{l.outStockExec.edit.warehouse}' . static::chooseWarehouse(callback: 'getPosition') . '</div>', '{l.outStockExec.edit.position}', '{l.outStockExec.edit.batch}', '{l.outStockExec.edit.batchInventory}', '{l.outStockExec.edit.nowNum}', '{l.outStockExec.edit.packing_quantity}', '{l.outStockExec.edit.box_capacity}', '{l.outStockExec.edit.remainder}', '{l.inStockExec.edit.price}', '{l.feeApply.home.money}'];
        $numTotal = $moneyTotal = 0;
        // 来源待出库单
        if ($this->get('ids')) {
            $target = query("inventory", " id = '" . $this->get('targetId') . "' ");
            //主表信息
            $info['type']             = $target['type'];
            $info['targetId']         = $target['targetId'];
            $info['sourceTargetName'] = self::getCompanyName($target['targetId']);

            $mxIdArr = array_filter(explode('/', $this->get('ids')));
            foreach ($mxIdArr as $k=>$detailId) {
                $inventory_detail             = query("inventory_detail", " id = '" . $detailId . "' ");
                // 如果出库前需要先完成质检，并且是待质检，则不能出库
                if(optionSettingClass::getSettingItem('库存', 'outStockQuality') && $inventory_detail['quality'] == 1){
                    continue;
                }
                $inventory                    = query("inventory", " id = '" . $inventory_detail['orderId'] . "' ", "orderNo");
                $material                     = query('material', "id = '$inventory_detail[materialId]'");
                $id                           = static::getId();
                $positionId                   = $inventory_detail['positionId'] ?: ($inventory_detail['warehouseId'] ? inventoryBalanceClass::matchLocation($inventory_detail['warehouseId']) : '');
                $warehouseSel                 = select(array(
                    'name'   => 'warehouseId[]',
                    'option' => toolOverhaulOutClass::warehouseOption($material['id']),
                    'change' => 'getPosition',
                    'title'  => '仓库',
                    'value'  => $inventory_detail['warehouseId']
                ));
                $position                     = selectMultiple([
                    "name"   => "positionId[]",
                    'option' => toolOverhaulOutClass::positionOption($material['id'], $inventory_detail['warehouseId']),
                    'title'  => L('inStockExec.edit.position'),
                    'change' => 'getBatch',
                    'value'  => $positionId
                ]);
                $batch                        = selectMultiple([
                    "name"   => "batch[]",
                    'option' => toolOverhaulOutClass::getBatchOption($material['id'], $inventory_detail['warehouseId'], $positionId),
                    'title'  => L('outStockExec.addWaitPutInEdit.choice'),
                    'change' => 'getBatchInventory',
                    'value'  => $inventory_detail['batch']
                ]);
                $putOut                       = find(array(
                    'table'  => static::tableRecord,
                    'single' => "inventoryMxId = '$inventory_detail[id]'",
                    'field'  => " IFNULL(sum(num),0)*-1 as num "
                ));
                $notOut                       = $inventory_detail['orderNum'] - $putOut['num'];
                $inventory_detail['orderNum'] = static::lostZero($inventory_detail['orderNum'], 'numPrecision');
                $putOut['num']                = static::lostZero($putOut['num'], 'numPrecision');
                $batchInventory               = inventoryBalanceClass::inventoryNum($material['id'], $inventory_detail['warehouseId'], $positionId);
                $price                        = inventoryBalanceClass::unitPrice($material['id']);  //出库均价
                $money                        = self::formattingFigure($notOut * $price);
                $tr[]                         =
                    [
                        componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $material['id']]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => 'inventory_detail']) .
                        hidden(['name' => 'sourceId[]', 'value' => $detailId]),
                        $inventory['orderNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        static::lostZero($inventory_detail['orderNum'], 'numPrecision'),
                        static::lostZero($putOut['num'], 'numPrecision'),
                        $warehouseSel,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='batchInventory'>$batchInventory</span>",
                        text([
                            'name'  => 'num[]',
                            'blur'  => 'countMoney',
                            'value' => static::lostZero($notOut, 'numPrecision'),
                            'other' => static::digitalFiltering('numPrecision')
                        ]),
                        text(['name' => 'packing_quantity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]),
                        text(['name' => 'box_capacity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]),
                        text(['name' => 'remainder[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]),
                        readOnlyInput(array("name" => "price[]", "value" => $price)),
                        readOnlyInput(array("name" => "money[]", "value" => $money)),
                    ];
                $numTotal                     += $notOut;
                $moneyTotal                   += $money;
            }
        } else {
            $inventorySetting = optionSettingClass::getSetting('库存');
            $checkCtrl        = $inventorySetting['checkCtrl'];// 库存是否需要复核
            $result           = find(array('table' => static::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ((array)$result['array'] as $k=>$array) {
                $material = query('material', " id = '$array[materialId]'");
                $putOut   = $array['sourceId'] ?
                    static::lostZero(find(array(
                        'table'  => static::tableRecord,
                        'single' => "inventoryMxId = '$array[sourceId]'", 'field' => " IFNULL(sum(num),0)*-1 as num "
                    ))['num'], 'numPrecision') :
                    '';
                //待出库可编辑
                if ($info['state'] == '待出库') {
                    $del       = componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal();");
                    $warehouse = select(array(
                        'name'   => 'warehouseId[]',
                        'option' => toolOverhaulOutClass::warehouseOption($material['id']),
                        'title'  => '仓库',
                        'change' => 'getPosition',
                        'value'  => $array['warehouseId']
                    ));
                    $position  = selectMultiple([
                        "name"   => "positionId[]",
                        'option' => toolOverhaulOutClass::positionOption($material['id'], $array['warehouseId']),
                        'title'  => L('inStockExec.edit.position'),
                        'change' => 'getBatch',
                        'value'  => $array['positionId']
                    ]);
                    $batch     = selectMultiple([
                        "name"   => "batch[]",
                        'option' => toolOverhaulOutClass::getBatchOption($material['id'], $array['warehouseId'], $array['positionId']),
                        'title'  => L('outStockExec.edit.choice'),
                        'change' => 'getBatchInventory',
                        'value'  => $array['batch']
                    ]);
                    $price     = empty($array['sourceId']) ?
                        text(['name' => 'price[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'), 'other' => self::digitalFiltering('pricePrecision')]) :
                        readOnlyInput(array("name" => "price[]", "value" => self::lostZero($array['price'], 'pricePrecision')));
                    $money     = empty($array['sourceId']) ?
                        text(['name' => 'money[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['money']), 'other' => self::digitalFiltering()]) :
                        readOnlyInput(array("name" => "money[]", "value" => self::lostZero($array['money'])));

                    $packing_quantity = text(['name' => 'packing_quantity[]', 'value' => static::lostZero($array['packing_quantity'], 'numPrecision'), 'other' => static::digitalFiltering('numPrecision')]);
                    $box_capacity     = text(['name' => 'box_capacity[]', 'value' => static::lostZero($array['box_capacity'], 'numPrecision'), 'other' => static::digitalFiltering('numPrecision')]);
                    $remainder        = text(['name' => 'remainder[]', 'value' => static::lostZero($array['remainder'], 'numPrecision'), 'other' => static::digitalFiltering('numPrecision')]);
                } else {
                    $del                = componentClass::tablePperation($k+1,"");
                    $warehouse          = query("warehouse", " id = '" . $array['warehouseId'] . "' ", "name");
                    $warehouse_position = query("warehouse_position", " id = '" . $array['positionId'] . "' ", "name");
                    $warehouse          = $warehouse['name'] . hidden(array("name" => "warehouseId[]", "value" => $array['warehouseId']));
                    $position           = $warehouse_position['name'] . hidden(array("name" => "positionId[]", "value" => $array['positionId']));
                    $batch              = $array['batch'] . hidden(array("name" => "batch[]", "value" => $array['batch']));
                    $price              = readOnlyInput(array("name" => "price[]", "value" => self::lostZero($array['price'], 'pricePrecision')));
                    $money              = readOnlyInput(array("name" => "money[]", "value" => self::lostZero($array['money'])));
                    $packing_quantity   = static::lostZero($array['packing_quantity'], 'numPrecision');
                    $box_capacity       = static::lostZero($array['box_capacity'], 'numPrecision');
                    $remainder          = static::lostZero($array['remainder'], 'numPrecision');
                }
                $num            = ($info['state'] == '待出库' || ($info['state'] == '已出库' && $checkCtrl)) ?
                    text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => static::lostZero($array['num'], 'numPrecision'), 'other' => static::digitalFiltering('numPrecision')]) :
                    self::lostZero($array['num'], 'numPrecision');
                $batchInventory = inventoryBalanceClass::inventoryNum($material['id'], $array['warehouseId'], $array['positionId'], $array['batch']);
                $tr[]           =
                    [
                        $del .
                        hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                        hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]) .
                        hidden(['name' => 'unit[]', 'value' => $array['unit'],]) .
                        hidden(['name' => 'sourceTable[]', 'value' => $array['sourceTable'],]) .
                        hidden(['name' => 'sourceId[]', 'value' => $array['sourceId'],]),
                        $array['sourceNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $array['unit'],
                        $array['sourceId'] ? static::lostZero($array['orderNum'], 'numPrecision') : '',
                        $putOut,
                        $warehouse,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='batchInventory'>$batchInventory</span>",
                        $num,
                        $packing_quantity,
                        $box_capacity,
                        $remainder,
                        $price,
                        $money,
                    ];
                $numTotal       += $array['num'];
                $moneyTotal     += $array['money'];
            }
        }
        $total_tr = [
            12 => "<span class='numTotal'>".self::lostZero($numTotal, 'numPrecision')."</span>",
            17 => "<span class='moneyTotal'>".self::lostZero($moneyTotal)."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
        $page = static::page;
        $but  = "";
        if (!$info['state'] || $info['state'] == '待出库') {
            $but = "<span class='smallButton' onclick='chooseWait()'>" . L('outStockExec.edit.chooseWait') . "</span>
                    <span class='smallButton' onclick=\"layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())\">" . L('outStockExec.edit.chooseMaterial') . "</span>";
        }
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('outStockExec.edit.type') => selectMultiple([
                        'option' => static::source,
                        "title"  => L('outStockExec.edit.choice'),
                        'name'   => 'type',
                        'value'  => $info['type']
                    ]),
                    L('outStockExec.edit.target')      => text(array(
                            'name'  => 'sourceTargetName',
                            'id'    => 'target',
                            'value' => $info['sourceTargetName']))
                        . hidden(array('name' => 'targetId', 'value' => $info['targetId'])) .
                        "<span class='del-row-button' onclick=\"newIframe('客户档案','" . root . "control/adIndex.html?cla=clientProfile&fun=edit')\" >新建客户</span>&nbsp;&nbsp;&nbsp;" .
                        "<span class='del-row-button' onclick=\"newIframe('供应商详情','" . root . "control/adIndex.html?cla=supplier&fun=edit')\" >新建供应商</span>",
                    L('outStockExec.homeListSearch.time') => text(['name' => "recordDate", 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date]),
                ],
                [
                    L('outStockExec.edit.text')           => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('outStockExec.edit.outMx'),
            'button' => $but,
            'html' => $list,
        ]);
        //表单
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $cla          = static::page;
        $data['html'] .= <<<efo
<script>
$(function() {
  inventoryWarning()
})
$("#target").bigAutocomplete({
        url:root + 'control/adIndex.html?cla=inStockExec&fun=getTarget',
        callback:function(data){
            $("[name='targetId']").val(data.id);
        }
    });
function addRow(type=''){
    if(type == 'addWaitPutIn'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addWaitPutInEdit',$("form[name='orderForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            calculateTotal()
            inventoryWarning()
            resetNumber($("#materialTable"))
        },'json');
    }else{
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            inventoryWarning()
            resetNumber($("#materialTable"))
        },'json');
    }
}
function chooseWait() {
    layer('{$this->get('cla')}','addWaitPutIn',$('form[name=outStockExecEditForm]').serialize())
}
//根据仓库获取库位
function getPosition(e){
    let par = $(e).parents('tr')
    let warehouseId = e.value;
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getPosition',{warehouseId:warehouseId,materialId:materialId},function(res) {
          par.find(".position").html(res.position);
          par.find(".batch").html(res.batch);
          par.find(".batchInventory").html(res.inventory);
    },'json');
}
//根据仓库获取批次
function getBatch(e){
    let positionId = $(e).val();
    let par = $(e).parents('tr')
    let warehouseId = par.find("[name='warehouseId[]']").val();
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getBatch',{positionId:positionId,warehouseId:warehouseId,materialId:materialId},function(res) {
          par.find(".batch").html(res.batch);
          par.find(".batchInventory").html(res.inventory);
    },'json');
}
//获取批次库存
function getBatchInventory(e){
    let batch = e.value;
    let materialId = $(e).parents("td").parent().find("[name='materialId[]']").val();
    let warehouseId = $(e).parents("td").parent().find("[name='warehouseId[]']").val();
    let positionId = $(e).parents("td").parent().find("[name='positionId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getBatchInventory',{warehouseId:warehouseId,positionId:positionId,materialId:materialId,batch:batch},function(res) {
          $(e).parents("td").parent().find(".batchInventory").html(res.inventory);
          inventoryWarning()
    },'json');
}
function countMoney(e) {
    let currentKey = $(e).attr('name')
    let par = $(e).parent().parent()
    let numNode = par.find("[name='num[]']")
    let priceNode = par.find("[name='price[]']")
    let moneyNode = par.find("[name='money[]']")
    let num = numNode.val()*1
    let price = priceNode.val()*1
    let money = moneyNode.val()*1
    if(currentKey === 'num[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'price[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'money[]'){
        if(num > 0){
            priceNode.val((money / num).toFixed(publicSettings.pricePrecision.num)).trigger('input')
        }else if(price > 0){
            numNode.val((money / price).toFixed(publicSettings.numPrecision.num))
        }
    }
    calculateTotal()
    inventoryWarning()
}
//计算总金额，总税额
function calculateTotal(){
    let num = 0,
    money = 0;
    $(".editList").find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var moneyValue = $(".editList").find("[name='money[]']").eq(index).val()
        if(moneyValue){
            money+=Number(moneyValue);
        }
    })
    $(".numTotal").text(num.toFixed(publicSettings.numPrecision.num));
    $(".moneyTotal").text(money.toFixed(amountPrecision));
}
/*库存不足提醒*/
function inventoryWarning() {
    $("[name='num[]']").each(function () {
        let num = $(this).val()*1
        let tr = $(this).parents("tr")
        let stock = tr.find(".batchInventory").text()*1
        tr.removeClass('warning')
        if(num > stock){
            tr.addClass('warning')
            tr.attr('title','库存不足')
        }
    });
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /** 根据仓库获取库位
     * @param string $warehouseId
     * @param string $materialId
     * @return mixed
     */
    public function getPosition($warehouseId = '', $materialId = ''): mixed
    {
        $warehouseId    = $warehouseId ?: $this->post('warehouseId');
        $materialId     = $materialId ?: $this->post('materialId');
        $option         = $batchOption = [];
        $positionId     = $batch = '';
        $batchInventory = 0;
        if ($warehouseId) {
            // 库位
            $option     = toolOverhaulOutClass::positionOption($materialId, $warehouseId);
            $positionId = array_key_first($option);
            //批号
            $batchOption    = toolOverhaulOutClass::getBatchOption($materialId, $warehouseId, $positionId);
            $batch          = array_key_first($batchOption);
            $batchInventory = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $positionId, $batch);
        }

        //库位
        $json['position'] = selectMultiple([
            "name"   => "positionId[]",
            'value'  => $positionId,
            'option' => $option,
            'title'  => L('inStockExec.edit.position'),
            'change' => 'getBatch'
        ]);
        //批号
        $json['batch']     = selectMultiple([
            "name"   => "batch[]",
            'option' => $batchOption,
            'title'  => L('outStockExec.edit.choice'),
            'change' => 'getBatchInventory',
            'value'  => $batch
        ]);
        $json['inventory'] = $batchInventory;
        return json_encode($json, 320);
    }

    /** 根据库位获取批次
     * @param string $warehouseId
     * @param string $positionId
     * @param string $materialId
     * @return mixed
     */
    public function getBatch($warehouseId = '', $positionId = '', $materialId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $positionId  = $positionId ?: $this->post('positionId');
        $materialId  = $materialId ?: $this->post('materialId');
        //批号
        $option            = toolOverhaulOutClass::getBatchOption($materialId, $warehouseId, $positionId);
        $batchInventory    = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $positionId, array_key_first($option));
        $json['batch']     = selectMultiple([
            "name"   => "batch[]",
            'option' => $option,
            'title'  => L('outStockExec.edit.choice'),
            'change' => 'getBatchInventory',
            'value'  => array_key_first($option)
        ]);
        $json['inventory'] = $batchInventory;
        return json_encode($json, 320);
    }

    /**
     * 获取批次库存
     */
    public function getBatchInventory(): bool|string
    {
        $warehouseId = $this->post('warehouseId');
        $positionId  = $this->post('positionId');
        $materialId  = $this->post('materialId');
        $batch       = $this->post('batch');
        //当前批次库存
        $batchInventory    = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $positionId, $batch);
        $json['inventory'] = $batchInventory;
        return json_encode($json, 320);
    }

    /**
     * 获取往来单位
     *
     * @return array
     */
    final public static function currentCompany(): array
    {
        $res = static::sqlFind(" select khid as id,concat(orderNo,'-',companyName) as name from kehu where coid = '" . static::$coid . "' UNION ALL select id,concat(code,'-',name) as name from supplier where coid = '" . static::$coid . "' ");
        return array_column($res, 'name', 'id');
    }

    /**获取往来单位名称
     *
     * @param string $targetId
     * @return string
     */
    final public static function getCompanyName($targetId = ''): string
    {
        $target = '';
        if ($targetId) {
            $target = query('kehu', " khid = '$targetId' ")['companyName'];
            if (empty($target)) {
                $target = query('supplier', " id = '$targetId' ")['name'];
            }
        }
        return $target;
    }


    /**
     * 选择仓库s
     *
     * @return string
     */
    public static function chooseWarehouse(string $obj = '', string $callback = ''): string
    {
        $obj    = $obj ?: 'warehouseId';
        $result = find(array(
            'table' => 'warehouse',
            'where' => " coid = '" . static::$coid . "' AND state = '启用' " . static::getWarehouseSql() . " order by time desc"
        ));
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>" . L('outStockExec.chooseWarehouse.choice') . "</li>";
        }
        $batchWord = L('outStockExec.chooseWarehouse.batch');
        return <<<EOT
        <span class='del-row-button' id='chooseWareHouse'>$batchWord</span><div class='stateBlock' style="margin-top: 7px;"><ul>$li</ul></div>
        <script>
         //点击非下拉区域隐藏
        $(document).bind('click', function (e) {
            let target = $(".stateBlock");
            let obj = $(".warehouse");
            if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
              target.hide();
            }
        });
        $("#chooseWareHouse").on('click',function() {
           $(".stateBlock").show();
        })
        $(".warehouse .stateBlock li").on('click',function() {
            let id = $(this).data('id');
            $("select[name='{$obj}[]']").each(function() {
              let obj = $(this);
              obj.val(id);
              $callback(this)
            });
           
           $(".stateBlock").hide();
        })
        </script>    
EOT;
    }

    public function editEdit()
    {
        $id                  = $this->post('id') ?: static::getId();
        $mxIdArr             = $this->post('mxId') ?: [];
        $materialIdArr       = $this->post('materialId');
        $unitArr             = $this->post('unit');
        $warehouseArr        = $this->post('warehouseId');
        $positionIdArr       = $this->post('positionId');
        $numArr              = $this->post('num');
        $batchArr            = $this->post('batch');
        $priceArr            = $this->post('price');
        $sourceTableArr      = $this->post('sourceTable');
        $sourceIdArr         = $this->post('sourceId');
        $packing_quantityArr = $this->post('packing_quantity');
        $box_capacityArr     = $this->post('box_capacity');
        $remainderArr        = $this->post('remainder');

        $field      = [
            'type'             => $this->post('type'),
            'sourceTargetName' => $this->post('sourceTargetName'),
            'targetId'         => $this->post('targetId'),
            'recordDate'       => $this->post('recordDate'),
            'text'             => $this->post('text'),
        ];
        $annotation = [
            'type'     => L('outStockExec.editEdit.type'),
            'targetId' => L('outStockExec.editEdit.targetId'),
            'text'     => L('outStockExec.editEdit.text'),
        ];
        $rules      = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where     = " id = '$id' ";
        $info      = query(static::table, $where);
        $checkCtrl = optionSettingClass::getSettingItem('库存', 'checkCtrl');// 库存是否需要复核
        //判断
        if (!$this->power(static::power, "edit")) {
            $json['warn'] = L('outStockExec.editEdit.power');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('outStockExec.editEdit.outMx');
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = L('outStockExec.editEdit.outMx');
        } elseif (static::is_null_array($warehouseArr)) {
            $json['warn'] = L('outStockExec.editEdit.outWarehouse');
        } elseif (static::is_null_array($positionIdArr)) {
            $json['warn'] = L('outStockExec.editEdit.outPosition');
        } elseif (static::is_null_array($numArr, false)) {
            $json['warn'] = L('outStockExec.editEdit.num') . '，且不能为0';
        } elseif (!empty($info['id']) && (in_array($info['state'], ['已复核', '已作废']) || (!$checkCtrl && $info['state'] == '已出库'))) {
            $json['warn'] = L('outStockExec.editEdit.cannotModified');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            //更新基础数据
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(static::power, [
                    'prefix' => 'CKD' . date('Ymd'),
                    'table'  => static::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . static::$coid . "' ",
                ], $field);
                $field        = array_merge($field, [
                    'id'       => $id,
                    'orderNo'  => $orderNo,
                    'classify' => 0,
                    'state'    => '待出库',
                    'coid'     => static::$coid,
                    'stid'     => $this->control['stid'],
                    'time'     => $this->post('recordDate') ?: $this->time,
                ]);
                $json['warn'] = static::insert(["table" => static::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => static::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx = query(static::tableMx, "id = '$nid'");
                    //获取源单数据
                    $orderNum = 0;
                    $sourceNo = "";
                    $price    = $priceArr[$k] ?: 0;
                    if (!empty($sourceIdArr[$k])) {
                        $source    = query($sourceTableArr[$k], "id = '$sourceIdArr[$k]'");
                        $inventory = query("inventory", "id = '$source[orderId]'");
                        $orderNum  = $source['orderNum'];
                        $sourceNo  = $inventory['orderNo'];
                        $price     = inventoryBalanceClass::unitPrice($materialIdArr[$k]);  //出库均价
                    }

                    $numArr[$k] = static::formattingFigure($numArr[$k], 'numPrecision');
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => static::tableMx,
                            "field" => [
                                'packing_quantity' => $packing_quantityArr[$k],
                                'box_capacity'     => $box_capacityArr[$k],
                                'remainder'        => $remainderArr[$k],
                                'warehouseId'      => $warehouseArr[$k],
                                'positionId'       => $positionIdArr[$k],
                                'num'              => $numArr[$k],
                                'batch'            => $batchArr[$k],
                                'price'            => $price,
                                'money'            => self::formattingFigure($price * $numArr[$k]),
                            ],
                            "where" => " id = '$nid'",
                        ]);
                        //未复核前可以修改出库数量
                        if ($info['state'] == '已出库') {
                            // 转换主单位
                            $editNum = $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $numArr[$k], $mx['unit']);
                            //修改已出库记录数量
                            $result = query(static::tableRecord, " changesId = '$nid' and num < 0 ");
                            static::update([
                                "table" => static::tableRecord,
                                "field" => [
                                    'num' => -1 * $editNum,
                                ],
                                "where" => " id = '{$result['id']}' and coid = '" . static::$coid . "' ",
                            ]);
                            //如果关联了源单，则进行源单相关数据处理
                            if (!empty($sourceIdArr[$k])) {
                                //修改线边库存
                                static::update([
                                    "table" => 'line_inventory',
                                    "field" => [
                                        'num' => -$mainUnitNum,
                                    ],
                                    "where" => " changesId = '$nid' and coid = '" . static::$coid . "' ",
                                ]);
                                //更新账户变动记录
                                $money  = round($numArr[$k] * $source['price'] * (1 + $source['rate']), 2);
                                $record = find(array(
                                    'table'  => 'record',
                                    'single' => " changesId = '$nid' and coid = '" . static::$coid . "' ",
                                    'field'  => " IFNULL(sum(money),0) as total "
                                ));
                                $total  = abs($record['total']);
                                // 关联表
                                $targetDate = $inventory['orderDate'];
                                $targetNo   = $targetText = $hiddenText = ' ';
                                if ($inventory['sourceTable']) {
                                    $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                    if (!empty($obj['id'])) {
                                        $targetDate = $obj['recordDate'];
                                        $targetNo   = $obj['orderNo'];
                                        $targetText = $inventory['type'] . "单【{$obj['orderNo']}】";
                                        $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，出库单ID：' . $source['orderId'] . '出库单子ID：' . $source['id'];
                                    }
                                }
                                if ($record['total'] < 0) {
                                    $changeMoney = $money > $total ? $money - $total : -($total - $money);
                                } else {
                                    $changeMoney = $money - $total;
                                }
                                $bool = supplierClass::insertRecord(
                                    $inventory['targetId'],
                                    $inventory['type'],
                                    $changeMoney,
                                    'inventory_detail',
                                    $source['id'],
                                    $targetDate,
                                    $targetNo,
                                    $targetText,
                                    $hiddenText,
                                    $nid
                                );
                                if ($bool !== true) {
                                    $json['warn'] = $bool;
                                    goto resp;
                                }
                                //修改源单出库状态
                                $outNum      = $source['num'] - $mx['num'] + $numArr[$k];
                                $detailMoney = self::formattingFigure($outNum * $source['price'] * (1 + $source['rate']));
                                static::update([
                                    'table' => 'inventory_detail',
                                    'field' => [
                                        'num'   => $outNum,
                                        'money' => $detailMoney,
                                    ],
                                    'where' => " id = '{$source['id']}' ",
                                ]);
                                $notOut = find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and num < orderNum and coid = '" . static::$coid . "' and id <> '" . $source['id'] . "'",
                                    'field'  => " IFNULL(count(id),0) as num "
                                ));
                                if ($outNum >= $source['orderNum'] && $notOut['num'] == 0) {
                                    static::update([
                                        'table' => 'inventory',
                                        'field' => [
                                            'state'       => '已出库',
                                            'confirmTime' => $info['confirmTime'],
                                        ],
                                        'where' => " id = '{$inventory['id']}' ",
                                    ]);
                                } elseif ($inventory['state'] != '部分出库') {
                                    static::update([
                                        'table' => 'inventory',
                                        'field' => [
                                            'state'      => '部分出库',
                                            'commitTime' => $this->time,
                                        ],
                                        'where' => " id = '{$inventory['id']}' ",
                                    ]);
                                }
                            }
                        }
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => static::tableMx,
                            "field" => [
                                'id'               => $nid,
                                'coid'             => static::$coid,
                                'orderId'          => $id,
                                'materialId'       => $materialIdArr[$k],
                                'orderNum'         => $orderNum,
                                'batch'            => $batchArr[$k],
                                'num'              => $numArr[$k],
                                'unit'             => $unitArr[$k],
                                'price'            => $price,
                                'money'            => self::formattingFigure($price * $numArr[$k]),
                                'warehouseId'      => $warehouseArr[$k],
                                'positionId'       => $positionIdArr[$k],
                                'sourceTable'      => $sourceTableArr[$k],
                                'sourceId'         => $sourceIdArr[$k],
                                'sourceNo'         => $sourceNo,
                                'packing_quantity' => $packing_quantityArr[$k],
                                'box_capacity'     => $box_capacityArr[$k],
                                'remainder'        => $remainderArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => static::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('outStockExec.editEdit.log'));
                $this->logText(["type" => static::power, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . static::page . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 批量作废
     *
     * @return bool|string
     */
    public function cancelEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::power, "cancel")) {
            $json['warn'] = L('outStockExec.cancel.power');
        } elseif (empty($array)) {
            $json['warn'] = L('outStockExec.cancel.none');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] != '已出库') {
                    $warn = L('outStockExec.cancel.fail');
                } else {
                    $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($result['array'] as $k => $mx) {
                        // 转换主单位
                        $mainUnitNum = 0;
                        //未复核前可以修改出库数量
                        $warn = static::update([
                            "table" => self::tableRecord,
                            "field" => [
                                'num' => $mainUnitNum,
                            ],
                            "where" => " changesId = '" . $mx['id'] . "' and coid = '" . self::$coid . "' ",
                        ]);
                        //有关联出库单，并且单据数量不是0
                        if (!empty($mx['sourceId']) && $mx['num'] != 0) {
                            $source    = query($mx['sourceTable'], "id = '" . $mx['sourceId'] . "'");
                            $inventory = query("inventory", "id = '$source[orderId]'");
                            //修改线边库存
                            static::update([
                                "table" => 'line_inventory',
                                "field" => [
                                    'num' => $mainUnitNum,
                                ],
                                "where" => " changesId = '" . $mx['id'] . "' and coid = '" . self::$coid . "' ",
                            ]);
                            //更新账户变动记录
                            $money  = 0;
                            $record = find(array(
                                'table'  => 'record',
                                'single' => " changesId = '" . $mx['id'] . "' and coid = '" . static::$coid . "' ",
                                'field'  => " IFNULL(sum(money),0) as total "
                            ));
                            $total  = abs($record['total']);
                            // 关联表
                            $targetDate = $targetNo = $targetText = $hiddenText = ' ';
                            if ($inventory['sourceTable']) {
                                $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                if (!empty($obj['id'])) {
                                    $targetDate = $obj['recordDate'];
                                    $targetNo   = $obj['orderNo'];
                                    $targetText = $inventory['type'] . "单【{$obj['orderNo']}】";
                                    $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，出库单ID：' . $source['orderId'] . '出库单子ID：' . $source['id'];
                                }
                            }
                            if ($record['total'] < 0) {
                                $changeMoney = $money > $total ? $money - $total : -($total - $money);
                            } else {
                                $changeMoney = $money - $total;
                            }
                            $bool = supplierClass::insertRecord(
                                $inventory['targetId'],
                                $inventory['type'],
                                $changeMoney,
                                'inventory_detail',
                                $source['id'],
                                $targetDate,
                                $targetNo,
                                $targetText,
                                $hiddenText,
                                $mx['id']
                            );
                            if ($bool !== true) {
                                $warn = L('outStockExec.editEdit.fail');
                                goto resp;
                            }
                            //修改源单出库状态
                            $outNum = $source['num'] - $mx['num'] + 0;
                            static::update([
                                'table' => 'inventory_detail',
                                'field' => [
                                    'num' => $outNum,
                                ],
                                'where' => " id = '{$source['id']}' ",
                            ]);

                            $inventoryState = '';
                            if (find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and num = 0 and coid = '" . self::$coid . "'", 'field' => " IFNULL(count(id),0) as num "
                                ))['num'] == find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and coid = '" . self::$coid . "'",
                                    'field'  => " IFNULL(count(id),0) as num "
                                ))['num']) {
                                $inventoryState = '待出库';
                            } elseif ($inventory['state'] != '部分出库') {
                                $inventoryState = '部分出库';
                            }
                            if ($inventoryState) {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'      => $inventoryState,
                                        'commitTime' => $this->time,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            }
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            goto resp;
                        }
                    }
                    static::update([
                        'table' => self::table,
                        'field' => [
                            'state' => '已作废',
                        ],
                        'where' => " id = '{$id}' ",
                    ]);
                    //返回
                    $warn = L('outStockExec.cancel.success');
                    $x++;
                }
                resp:
                $text .= str_replace(['{{id}}'], [$info['id']], lang('outStockExec.cancel.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('outStockExec.cancel.log')) . "<br>" . $text;
            $this->logText(array("type" => self::printPage, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('outStockExec.cancel.warn'));
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 关联待出库单
     *
     * @return bool|string
     */
    public function addWaitPutIn(): bool|string
    {
        $html   =
            text(array("name" => "orderNo", "title" => "{l.outStockExec.addWaitPutIn.orderNo}")) .
            text(array("name" => "code", "title" => "{l.outStockExec.addWaitPutIn.code}")) .
            text(array("name" => "materialName", "title" => "{l.outStockExec.addWaitPutIn.materialName}")) .
            text(array("name" => "model", "title" => "{l.outStockExec.addWaitPutIn.model}")) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"addRow('addWaitPutIn')\" type='button' class='searchSub' value='" . L('outStockExec.addWaitPutIn.continueAdding') . "'>";
        $button .= "<input style='margin-left: 5px' onclick=\"addRow('addWaitPutIn');$('#" . static::page . "AddWaitPutIn').remove()\" type='button' class='searchSub' value='" . L('outStockExec.addWaitPutIn.sub') . "'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => L('outStockExec.addWaitPutIn.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联待出库单
     *
     * @return bool|string
     */
    public function addWaitPutInSearch(): bool|string
    {
        $where = " main.coid='" . static::$coid . "' and main.state <> '已出库' ";
        $and   = "";
        $like  = [
            'main.orderNo' => $this->post('orderNo'),
            'mat.code'     => $this->post('code'),
            'mat.name'     => $this->post('materialName'),
            'mat.model'    => $this->post('model'),
        ];
        $equal = [
            'main.type'     => $this->post('type'),
            'main.classify' => 0,
        ];
        if ($this->post('targetId')) {
            //交货日期
            $and .= " and main.targetId = '" . $this->post('targetId') . "' ";
        }
        // 出库前是否需要先完成质检
        if(optionSettingClass::getSettingItem('库存', 'outStockQuality')){
            $and .= " and mx.quality <> 1 ";
        }
        $and   .= " and mx.orderNum - (select IFNULL(sum(num),0)*-1 as num from inventory_record where inventoryMxId = mx.id and num < 0) > 0 ";
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "inventory_detail as mx join inventory as main on mx.orderId = main.id join material as mat on mx.materialId = mat.id",
            "field"   => "mx.id,mx.orderNum,main.orderNo,mat.code,mat.name,mat.model,(select IFNULL(sum(num),0)*-1 as num from inventory_record where inventoryMxId = mx.id and num < 0) as putIn",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "main.`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("orderForm", "detailId");
        $tr[]     = [$checkAll, '{l.outStockExec.addWaitPutInSearch.orderNo}', '{l.outStockExec.addWaitPutInSearch.code}', '{l.outStockExec.addWaitPutInSearch.name}', '{l.outStockExec.addWaitPutInSearch.model}', '{l.outStockExec.addWaitPutInSearch.notOut}'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "detailId", "value" => $array['id']),
            );
            $tr[]     = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['orderNum'] - $array['putIn'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='orderForm'>" .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 关联待出库单
     */
    public function addWaitPutInEdit()
    {
        $mxIdArr = $this->post('detailId');
        if (!$this->power(static::power, 'edit')) {
            $json['warn'] = L('outStockExec.addWaitPutInEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('outStockExec.addWaitPutInEdit.noChoice');
        } else {
            $tr = [];
            foreach ($mxIdArr as $detailId) {
                $inventory_detail             = query("inventory_detail", " id = '" . $detailId . "' ");
                $inventory                    = query("inventory", " id = '" . $inventory_detail['orderId'] . "' ", "orderNo");
                $material                     = query('material', "id = '$inventory_detail[materialId]'");
                $id                           = static::getId();
                $positionId                   = $inventory_detail['positionId'] ?: ($inventory_detail['warehouseId'] ? inventoryBalanceClass::matchLocation($inventory_detail['warehouseId']) : '');
                $warehouseSel                 = select(array(
                    'name'   => 'warehouseId[]',
                    'option' => toolOverhaulOutClass::warehouseOption($material['id']),
                    'change' => 'getPosition',
                    'title'  => '仓库',
                    'value'  => $inventory_detail['warehouseId']
                ));
                $position                     = selectMultiple([
                    "name"   => "positionId[]",
                    'option' => toolOverhaulOutClass::positionOption($material['id'], $inventory_detail['warehouseId']),
                    'title'  => L('inStockExec.edit.position'),
                    'change' => 'getBatch',
                    'value'  => $positionId
                ]);
                $batchOption                  = toolOverhaulOutClass::getBatchOption($material['id'], $inventory_detail['warehouseId'], $positionId);
                $batchValue                   = $inventory_detail['batch'] && isset($batchOption[$inventory_detail['batch']]) ? $inventory_detail['batch'] : array_key_first($batchOption);
                $batch                        = selectMultiple([
                    "name"   => "batch[]",
                    'option' => $batchOption,
                    'title'  => L('outStockExec.addWaitPutInEdit.choice'),
                    'change' => 'getBatchInventory',
                    'value'  => $batchValue
                ]);
                $numFiltering                 = static::digitalFiltering('numPrecision');
                $putOut                       = find(array(
                    'table'  => static::tableRecord,
                    'single' => "inventoryMxId = '$inventory_detail[id]'",
                    'field'  => " IFNULL(sum(num),0)*-1 as num "
                ));
                $notOut                       = $inventory_detail['orderNum'] - $putOut['num'];
                $inventory_detail['orderNum'] = static::lostZero($inventory_detail['orderNum'], 'numPrecision');
                $putOut['num']                = static::lostZero($putOut['num'], 'numPrecision');
                $batchInventory               = inventoryBalanceClass::inventoryNum($material['id'], $inventory_detail['warehouseId'], $positionId, $batchValue);
                $price                        = inventoryBalanceClass::unitPrice($material['id']);  //出库均价
                $money                        = self::formattingFigure($notOut * $price);
                $packing_quantity             = text(['name' => 'packing_quantity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $box_capacity                 = text(['name' => 'box_capacity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $remainder                    = text(['name' => 'remainder[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $price                        = readOnlyInput(array("name" => "price[]", "value" => self::lostZero($price, 'pricePrecision')));
                $money                        = readOnlyInput(array("name" => "money[]", "value" => $money));
                $tr[]                         =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $material['id']]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => 'inventory_detail']) .
                        hidden(['name' => 'sourceId[]', 'value' => $detailId]),
                        $inventory['orderNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        static::lostZero($inventory_detail['orderNum'], 'numPrecision'),
                        static::lostZero($putOut['num'], 'numPrecision'),
                        $warehouseSel,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='batchInventory'>$batchInventory</span>",
                        text([
                            'name'  => 'num[]',
                            'blur'  => 'countMoney',
                            'value' => static::lostZero($notOut, 'numPrecision'),
                            'other' => static::digitalFiltering('numPrecision')
                        ]),
                        $packing_quantity,
                        $box_capacity,
                        $remainder,
                        $price,
                        $money,
                    ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /**
     * @return string
     */
    public function addMx(): string
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = '';
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "type", "value" => $this->post('type')])
                . hidden(["name" => "targetId", "value" => $this->post('targetId')]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(static::power, 'edit')) {
            $json['warn'] = L('outStockExec.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('outStockExec.addMxEdit.noChoice');
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material         = query('material', "id = '$mxId'");
                $id               = static::getId();
                $warehouseSel     = select(array(
                    'name'   => 'warehouseId[]',
                    'option' => toolOverhaulOutClass::warehouseOption($material['id']),
                    'title'  => '仓库',
                    'change' => 'getPosition'
                ));
                $position         = selectMultiple([
                    "name"   => "positionId[]",
                    'option' => toolOverhaulOutClass::positionOption($material['id'], '##'),
                    'title'  => L('inStockExec.edit.position'),
                    'change' => 'getBatch',
                    'value'  => ''
                ]);
                $batch            = selectMultiple([
                    "name"   => "batch[]",
                    'option' => toolOverhaulOutClass::getBatchOption($material['id'], '', ''),
                    'title'  => '请选择',
                    'change' => 'getBatchInventory',
                    'value'  => ''
                ]);
                $numFiltering     = static::digitalFiltering('numPrecision');
                $price            = text(['name' => 'price[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => inventoryBalanceClass::unitPrice($material['id'])]);
                $money            = text(['name' => 'money[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision')]);
                $packing_quantity = text(['name' => 'packing_quantity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $box_capacity     = text(['name' => 'box_capacity[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $remainder        = text(['name' => 'remainder[]', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $num = text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => '', 'other' => static::digitalFiltering('numPrecision')]);
                $tr[]           =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $mxId]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit'],]) .
                        hidden(['name' => 'sourceTable[]', 'value' => '']) .
                        hidden(['name' => 'sourceId[]', 'value' => '']),
                        '',
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        '--',
                        '--',
                        $warehouseSel,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='batchInventory'></span>",
                        $num,
                        $packing_quantity,
                        $box_capacity,
                        $remainder,
                        $price,
                        $money,
                    ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(static::table, " coid = '" . static::$coid . "' AND id = '{$this->get('id')}' ");
        if (empty($info['id'])) {
            $html = L('outStockExec.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            // 库存是否需要复核
            $checkCtrl = optionSettingClass::getSettingItem('库存', 'checkCtrl');
            $button    = [];
            if ($this->power(static::power, "edit") && ($info['state'] == '待出库' || ($info['state'] == '已出库' && $checkCtrl))) {
                //按钮
                /*$button[] = [
                    "name" => L('outStockExec.detail.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];*/
                //按钮
                $button[] = [
                    "name"  => L('outStockExec.detail.edit'),
                    "type"  => "顶部页卡",
                    "title" => L('outStockExec.detail.editOutStock'),
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(static::power, "edit") && $info['state'] == '待出库') {
                $button[] = [
                    "name"  => L('outStockExec.detail.sureOut'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(static::power, "check") && $info['state'] == '已出库' && $checkCtrl) {
                $button[] = [
                    "name" => L('outStockExec.detail.check'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'check', "id" => $info['id']],
                ];
            }
            $button[] = [
                "name" => "打印产品标识卡",
                "type" => "外部链接",
                "url"  => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=printCard&body=' . $info['id'],
            ];
            if ($this->power(self::power, "print")) {
                //按钮
                $button[] = [
                    "name" => "打印",
                    "type" => "点击事件",
                    "fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[]   = ['单据来源', '{l.outStockExec.detail.sourceNo}', '{l.outStockExec.detail.code}', '{l.outStockExec.detail.name}', '{l.outStockExec.detail.model}', '{l.outStockExec.detail.unit}', '{l.outStockExec.detail.warehosue}', '{l.outStockExec.edit.position}', '{l.outStockExec.detail.orderNum}', '{l.outStockExec.detail.outNum}', '{l.outStockExec.detail.nowNum}', '{l.outStockExec.edit.packing_quantity}', '{l.outStockExec.edit.box_capacity}', '{l.outStockExec.edit.remainder}', '{l.outStockExec.detail.batch}', '{l.inStockExec.edit.price}', '{l.outStockExec.edit.batchInventory}'];
            $result   = find(array('table' => static::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['orderNum'=>0,'putOut'=>0,'num'=>0];
            foreach ($result['array'] as $array) {
                $material  = query('material', " id = '$array[materialId]'");
                $sourceBut = '';
                if ($array['sourceId']) {
                    $putOut = find(array(
                        'table'  => static::tableRecord,
                        'single' => "inventoryMxId = '$array[sourceId]'",
                        'field'  => " IFNULL(sum(num),0)*-1 as num "
                    ));
                    //追溯源单
                    $inventory_detail = query("inventory_detail", " id = '" . $array['sourceId'] . "' ", "sourceTable,sourceId");
                    if ($inventory_detail['sourceTable'] == 'sale_send_order_detail') {
                        $sale_send_order_detail = query("sale_send_order_detail", " id = '" . $inventory_detail['sourceId'] . "' ", "orderId,saleOrderMxId");
                        $sale_order_detail      = query("sale_order_detail", " id = '" . $sale_send_order_detail['saleOrderMxId'] . "' ", "orderId");
                        if ($sale_order_detail['orderId']) {
                            $sourceBut .= " <span class='del-row-button' onclick=\"newIframe('销售订单详情','" . root . "control/adIndex.html?cla=saleOrder&fun=detail&id=" . $sale_order_detail['orderId'] . "')\">销售订单</span>";
                        }
                        if ($sale_send_order_detail['orderId']) {
                            $sourceBut .= " <span class='del-row-button'  onclick=\"newIframe('销售发货单详情','" . root . "control/adIndex.html?cla=saleSendOrder&fun=detail&id=" . $sale_send_order_detail['orderId'] . "')\">销售发货单</span>";
                        }
                    }
                } else {
                    $putOut['num'] = 0;
                }
                $price          = $array['price'];
                $batchInventory = inventoryBalanceClass::inventoryNum($material['id'], $array['warehouseId'], $array['positionId'], $array['batch']);
                $mxtr[]         = [
                    $sourceBut,
                    $array['sourceNo'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    static::lostZero($array['orderNum'], 'numPrecision'),
                    static::lostZero($putOut['num'], 'numPrecision'),
                    static::lostZero($array['num'], 'numPrecision'),
                    static::lostZero($array['packing_quantity'], 'numPrecision'),
                    static::lostZero($array['box_capacity'], 'numPrecision'),
                    static::lostZero($array['remainder'], 'numPrecision'),
                    $array['batch'],
                    $price,
                    $batchInventory,
                ];
                $totalArr['orderNum'] += $array['orderNum'];
                $totalArr['putOut'] += $putOut['num'];
                $totalArr['num'] += $array['num'];
            }
            $total_tr = [
                8=>self::lostZero($totalArr['orderNum'], 'numPrecision'),
                9=>self::lostZero($totalArr['putOut'], 'numPrecision'),
                10=>self::lostZero($totalArr['num'], 'numPrecision'),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        L('outStockExec.detail.source') => $info['type'],
                        L('outStockExec.detail.target') => $info['sourceTargetName'],
                        L('outStockExec.detail.orderNo') => $info['orderNo'],
                        L('outStockExec.detail.stid')    => static::findStaff($info['stid']),
                    ],
                    [
                        L('outStockExec.detail.state')   => $info['state'],
                    ],
                    [
                        L('outStockExec.detail.text') => pre($info['text']),
                    ],

                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('outStockExec.detail.outMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'end' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**合并相同物料，相同库位，相同批次的出库数量
     *
     * @param array $detail
     * @return float
     */
    final public static function mergeMaterialNum($detail): float
    {
        $total   = 0; //总数量
        $details = find([
            'table' => static::tableMx,
            'where' => " coid = '" . self::$coid . "' and orderId = '{$detail['orderId']}' and materialId = '{$detail['materialId']}' and positionId = '{$detail['positionId']}' and batch = '{$detail['batch']}' ",
        ]);
        foreach ((array)$details['array'] as $key => $value) {
            // 转换主单位
            $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
            $total       += $mainUnitNum;
        }
        return $total;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id          = $this->post('id');
        $confirmTime = $this->post('confirmTime');
        $info        = query(static::table, " coid = '" . static::$coid . "' AND id = '$id'");
        $field       = [
            'state'       => '已出库',
            'confirmTime' => $confirmTime,
        ];
        if (!$this->power(static::power, 'edit')) {
            $json['warn'] = L('outStockExec.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('outStockExec.confirmEdit.empty');
        } elseif (empty($confirmTime)) {
            $json['warn'] = '请选择出库时间';
        } elseif ($info['state'] != '待出库') {
            $json['warn'] = L('outStockExec.confirmEdit.stateError');
        } else {
            $this->startTrans();
            /***仓库允许零库存出库*/
            $outAllowZero  = optionSettingClass::getSettingItem('库存', 'outAllowZero');
            $outStockLimit = optionSettingClass::getSettingItem('库存', 'outStockLimit');  // 出库数量允许超过源单数量
            // 出库明细
            $details = find([
                'table' => static::tableMx,
                'where' => " orderId = '{$info['id']}'",
            ]);
            // 不允许负库存
            if (!$outAllowZero) {
                foreach ($details['array'] as $key => $value) {
                    $mergeMaterialNum = self::mergeMaterialNum($value);  // 合并相同物料，相同库位，相同批次的出库数量
                    $stock            = inventoryBalanceClass::inventoryNum($value['materialId'], $value['warehouseId'], $value['positionId'], $value['batch']);
                    if ($stock - $mergeMaterialNum < 0) {
                        $material     = query("material", " id = '" . $value['materialId'] . "' ", "name");
                        $json['warn'] = "【" . $material['name'] . "，批次" . $value['batch'] . "】" . L('outStockExec.confirmEdit.transfinite');
                        goto resp;
                    }
                }
            }
            $json['warn'] = update([
                "table" => static::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                foreach ($details['array'] as $key => $value) {
                    if ($value['num'] > 0) {
                        $material = query("material", " id = '" . $value['materialId'] . "' ", "id,name");
                        // 转换主单位
                        $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                        $price       = inventoryBalanceClass::unitPrice($material['id']);
                        $stock       = inventoryBalanceClass::inventoryNum($value['materialId'], $value['warehouseId'], $value['positionId'], $value['batch']);
                        if ($outAllowZero && $stock - $mainUnitNum < 0) {
                            //发送负库存预警
                            $setting = static::getSettingValue('inventoryNegative');
                            foreach ($setting['member'] as $item) {
                                message(array(
                                    "stid"      => $item,
                                    "type"      => '预警消息',
                                    "typeId"    => $value['materialId'],
                                    "text"      => "物料【" . $material['name'] . "】负库存预警",
                                    "targetCla" => 'inventoryBalance',
                                    "targetFun" => 'detail',
                                ));
                            }
                        }

                        $bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "down");  //最低库存控制
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            goto resp;
                        }
                        $inventory_detail = ['orderId' => '', 'id' => ''];
                        if ($value['sourceId']) {
                            $inventory_detail = query("inventory_detail", " id = '$value[sourceId]' ");
                            $inventory        = query("inventory", " id = '$inventory_detail[orderId]' ");
                            // 累计金额
                            $detailMoney = ($inventory_detail['num'] + $value['num']) * $inventory_detail['price'] * (1 + $inventory_detail['rate']);
                            $nowNum      = $inventory_detail['num'] + $value['num'];
                            if (!$outStockLimit && $nowNum > $inventory_detail['orderNum']) {
                                $json['warn'] = "【" . $material['name'] . "】出库数量不允许超过源单数量,源单剩余未出库数量【" . ($inventory_detail['orderNum'] - $inventory_detail['num']) . "】";
                                goto resp;
                            }
                            $json['warn'] = static::update([
                                "table" => 'inventory_detail',
                                "field" => [
                                    'num'   => $nowNum,
                                    'money' => $detailMoney,
                                ],
                                "where" => "id = '$inventory_detail[id]'",
                            ]);
                            if (!in_array($json['warn'], ["新增成功", "更新成功"])) {
                                goto resp;
                            }
                            //如果是配料出库，则生成线边库存记录
                            if ($inventory['type'] == '配料出库') {
                                $bool = tempInventoryClass::insertRecord(array(
                                    'lineId'        => $inventory['targetId'],
                                    'materialId'    => $inventory_detail['materialId'],
                                    'inventoryId'   => $inventory['id'],
                                    'inventoryMxId' => $inventory_detail['id'],
                                    'num'           => $mainUnitNum,
                                    'batch'         => $value['batch'],
                                    'changesId'     => $value['id'],
                                ));
                                if ($bool !== true) {
                                    $json['warn'] = $bool;
                                    goto resp;
                                }
                            }

                            //如果是生产领料且未关联生产计划单，也生成线边库存记录
                            if ($inventory['type'] == '生产领料') {
                                $pick_order_detail = query('pick_order_detail', "id = '$inventory_detail[sourceId]'");
                                if (!empty($pick_order_detail['id']) && empty($pick_order_detail['sourceId'])) {
                                    $bool = tempInventoryClass::insertRecord(array(
                                        'lineId'        => $inventory['targetId'],
                                        'materialId'    => $inventory_detail['materialId'],
                                        'inventoryId'   => $inventory['id'],
                                        'inventoryMxId' => $inventory_detail['id'],
                                        'num'           => $mainUnitNum,
                                        'batch'         => $value['batch'],
                                        'changesId'     => $value['id'],
                                    ));
                                    if ($bool !== true) {
                                        $json['warn'] = $bool;
                                        goto resp;
                                    }
                                }
                            }

                            // 关联表
                            $targetDate = $inventory['orderDate'];
                            $targetNo   = $targetText = $hiddenText = ' ';
                            if ($inventory['sourceTable']) {
                                $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                if (!empty($obj['id'])) {
                                    $targetDate = $obj['recordDate'];
                                    $targetNo   = $obj['orderNo'];
                                    $targetText = $inventory['type'] . "单【{$obj['orderNo']}】";
                                    $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，出库单ID：' . $inventory_detail['orderId'] . '出库单子ID：' . $inventory_detail['id'];
                                }
                            }
                            $bool = supplierClass::insertRecord(
                                $inventory['targetId'],
                                $inventory['type'],
                                self::formattingFigure($value['num'] * $inventory_detail['price'] * (1 + $inventory_detail['rate'])),
                                'inventory_detail',
                                $inventory_detail['id'],
                                $targetDate,
                                $targetNo,
                                $targetText,
                                $hiddenText,
                                $value['id']
                            );
                            if ($bool !== true) {
                                $json['warn'] = $bool;
                                goto resp;
                            }
                            //修改待出库单状态
                            $notOut = find(array(
                                'table'  => 'inventory_detail',
                                'single' => "orderId = '$inventory[id]' and num < orderNum and coid = '" . static::$coid . "' and id <> '" . $inventory_detail['id'] . "'",
                                'field'  => " IFNULL(count(id),0) as num "
                            ));
                            if ($nowNum >= $inventory_detail['orderNum'] && $notOut['num'] == 0) {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'       => '已出库',
                                        'confirmTime' => $confirmTime,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            } elseif ($inventory['state'] == '待出库') {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'      => '部分出库',
                                        'commitTime' => $this->time,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            }
                        }
                        if ($mainUnitNum > 0) {
                            $positionId = $value['positionId'];
                            insert([
                                'table' => static::tableRecord,
                                'field' => [
                                    'id'            => static::getNo(),
                                    'coid'          => static::$coid,
                                    'warehouseId'   => $value['warehouseId'],
                                    'positionId'    => $positionId,
                                    'materialId'    => $value['materialId'],
                                    'batch'         => $value['batch'],
                                    'num'           => -1 * $mainUnitNum,
                                    'inventoryId'   => $inventory_detail['orderId'],
                                    'inventoryMxId' => $inventory_detail['id'],
                                    'changesId'     => $value['id'],
                                    'defaultPrice'  => $price,
                                    'time'          => $confirmTime,
                                ],
                            ]);
                            if (!empty($positionId)) {
                                inventoryBalanceClass::recordStockToLocation('', ['materialId' => $value['materialId'], 'warehouseId' => $value['warehouseId'], 'positionId' => $positionId, 'batch' => $value['batch']]);
                            }
                        }
                    }
                }
                $this->commitTrans();//提交事务
                auditingFollow(array(
                    "type"   => "出库单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('outStockExec.confirmEdit.log'));
                $this->logText(["type" => static::power, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 复核
     */
    public function checkEdit()
    {
        $id    = $this->post('id');
        $info  = query(static::table, " coid = '" . static::$coid . "' AND id = '$id'");
        $field = [
            'state'      => '已复核',
            'reviewTime' => $this->time,
        ];
        if (!$this->power(static::power, 'check')) {
            $json['warn'] = L('outStockExec.checkEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('outStockExec.checkEdit.empty');
        } elseif ($info['state'] != '已出库') {
            $json['warn'] = L('outStockExec.checkEdit.stateError');
        } else {
            $json['warn'] = update(array(
                "table" => static::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow([
                    "type"   => "出库单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】复核",
                ]);

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('outStockExec.checkEdit.log'));
                $this->logText(["type" => static::power, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act    = $this->post('act') ?? '';
        $pwd    = $word = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'confirm':
                $act      = 'edit';
                $msg      = L('outStockExec.operate.sure');
                $title    = L('outStockExec.operate.sureTitle');
                $function = 'confirmEdit';
                $form     = static::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                $append   = [
                    must . '出库时间：' => text([
                            "name"    => "confirmTime",
                            "title"   => "出库时间",
                            "value"   => $this->time,
                            'laydate' => ['type' => 'datetime'],
                        ]) . space,
                ];
                break;
            case 'check':
                $act      = 'check';
                $msg      = L('outStockExec.operate.check');
                $title    = L('outStockExec.operate.checkTitle');
                $function = 'checkEdit';
                $form     = static::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'cancel': //作废
                $act      = 'cancel';
                $msg      = L('outStockExec.operate.cancel');
                $title    = L('outStockExec.operate.cancelTitle');
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, listForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'updateTime':
                $act      = 'edit';
                $msg      = '修改出库完成时间';
                $title    = '';
                $function = 'updateTime';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word     = true;
                $append   = [
                    [
                        must . '上班时间：' => text(["name" => "startTime", "laydate" => ['type' => 'time'], "title" => "上班时间", 'value' => '09:00:00']) . "-\n" .
                            text(["name" => "endTime", "laydate" => ['type' => 'time'], "title" => "下班时间", 'value' => '18:00:00'])
                    ],
                    [
                        must . '当前出库完成时间段：' => text(["name" => "nowStart", "laydate" => [], "title" => "当前出库完成时间段开始"]) . "-\n" .
                            text(["name" => "nowEnd", "laydate" => [], "title" => "当前出库完成时间段结束"])
                    ],
                    [
                        must . '期望出库完成时间段：' => text(["name" => "expectStart", "laydate" => [], "title" => "期望出库完成时间段开始"]) . "-\n" .
                            text(["name" => "expectEnd", "laydate" => [], "title" => "期望出库完成时间段结束"])
                    ]
                ];
                break;
            default:
                $act      = 'del';
                $msg      = L('outStockExec.operate.del');
                $title    = static::page . 'Delete';
                $function = 'delete';
                $form     = static::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(static::power, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('outStockExec.operate.warn'));
            $json             = [
                'warn' => 2,
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'append'   => $append,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改入库完成时间
     */
    public function updateTime()
    {
        $field      = [
            'startTime'   => $this->post('startTime'),
            'endTime'     => $this->post('endTime'),
            'nowStart'    => $this->post('nowStart'),
            'nowEnd'      => $this->post('nowEnd'),
            'expectStart' => $this->post('expectStart'),
            'expectEnd'   => $this->post('expectEnd'),
        ];
        $annotation = [
            'startTime'   => '上班时间',
            'endTime'     => '下班时间',
            'nowStart'    => '当前出库完成时间段开始',
            'nowEnd'      => '当前出库完成时间段结束',
            'expectStart' => '期望出库完成时间段开始',
            'expectEnd'   => '期望出库完成时间段结束',
        ];
        $rules      = [
            'startTime'   => 'required',
            'endTime'     => 'required',
            'nowStart'    => 'required|date',
            'nowEnd'      => 'required|date',
            'expectStart' => 'required|date',
            'expectEnd'   => 'required|date',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $where = self::timeComparison($field['nowStart'] . '~' . $field['nowEnd'], 'date', 'confirmTime');
            $mx    = find(array('table' => self::table, 'where' => " coid = '" . self::$coid . "' and classify = 0 and confirmTime is not null {$where}"));
            foreach ($mx['array'] as $value) {
                $confirmTime = date('Y-m-d', mt_rand(strtotime($field['expectStart']), strtotime($field['expectEnd']))) . ' ' . date('H:i:s', mt_rand(strtotime($field['startTime']), strtotime($field['endTime'])));
                $orderNo     = codeTemplateClass::generateCode(static::power, [
                    'prefix' => 'CKD' . date('Ymd', strtotime($confirmTime)),
                    'table'  => static::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . static::$coid . "' ",
                ], $value);
                update(array(
                    "table" => self::table,
                    "field" => ['orderNo' => $orderNo, 'confirmTime' => $confirmTime],
                    "where" => "id = '$value[id]'",
                ));
                //修改客户
                if ($value['targetId']) {
                    $target = query("kehu", " khid = '$value[targetId]' ", "khid,updateTime,time");
                    if (strtotime($confirmTime) < strtotime($target['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'kehu',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " khid = '$target[khid]' ",
                        ));
                    }
                }
                $res = find(array(
                    'table' => self::tableMx,
                    'field' => 'id,sourceId,materialId,warehouseId,positionId',
                    'where' => " coid = '" . self::$coid . "' and orderId = '$value[id]' "
                ));
                foreach ($res['array'] as $arr) {
                    update(array(
                        "table" => 'inventory_record',
                        "field" => ['time' => $confirmTime],
                        "where" => " changesId = '$arr[id]' ",
                    ));
                    //修改带出入库单
                    if ($arr['sourceId']) {
                        $inventory_detail = query("inventory_detail", " id = '$arr[sourceId]' ", "orderId");
                        $inventory        = query("inventory", " id = '$inventory_detail[orderId]' ", "sourceDate");
                        if ($inventory['sourceDate']) {
                            $time = $inventory['sourceDate'] . ' ' . date("H:i:s", mt_rand(strtotime('09:00:00'), strtotime('18:00:00')));
                            update(array(
                                "table" => 'inventory',
                                "field" => [
                                    'orderNo'    => codeTemplateClass::generateCode(self::power, [
                                        'prefix' => 'RKD' . date('Ymd', strtotime($inventory['sourceDate'])),
                                        'table'  => 'inventory',
                                        'field'  => 'orderNo',
                                        'where'  => " AND coid = '" . self::$coid . "' ",
                                    ], $inventory),
                                    'orderDate'  => $inventory['sourceDate'],
                                    'updateTime' => $time,
                                    'time'       => $time,
                                ],
                                "where" => " id = '$inventory_detail[orderId]' ",
                            ));
                        }
                    }
                    //修改物料
                    $material = query("material", " id = '$arr[materialId]' ", "id,updateTime,time");
                    if (strtotime($confirmTime) < strtotime($material['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'material',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$material[id]' ",
                        ));
                    }
                    //修改仓库
                    $warehouse = query("warehouse", " id = '$arr[warehouseId]' ", "id,updateTime,time");
                    if (strtotime($confirmTime) < strtotime($warehouse['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'warehouse',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$warehouse[id]' ",
                        ));
                    }
                    //修改库位
                    $warehouse_position = query("warehouse_position", " id = '$arr[positionId]' ", "id,updateTime,time");
                    if (strtotime($confirmTime) < strtotime($warehouse_position['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'warehouse_position',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$warehouse_position[id]' ",
                        ));
                    }
                }
            }
            //返回
            $_SESSION['warn'] = '操作成功';
            $json['warn']     = 2;
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(static::power, "del")) {
            $json['warn'] = L('outStockExec.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('outStockExec.delete.noChoice');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(static::table, " coid = '" . static::$coid . "' AND id = '$id' ");
                if ($info['state'] == '已复核') {
                    $warn = L('outStockExec.delete.fail');
                } elseif ($info['state'] == '已出库' && sqlNum(self::tableMx, " (coid = '" . self::$coid . "' AND orderId = '{$id}') AND num > 0   ") > 0) {
                    $warn = L('outStockExec.delete.numFail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => static::table, "where" => " id = '$id' "));
                    delete(array("table" => static::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('outStockExec.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], lang('outStockExec.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('outStockExec.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => static::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('outStockExec.delete.warn'));
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit(L('outStockExec.batchPrint.error'));
        } else {
            $listId = base64_decode($lists, true);
            $array  = explode(',', $listId);
            $data   = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(static::power, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id                  = $param ?: $this->get('id');
        $info                = query(static::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . static::$coid . "'")['name']; //公司名称
        $info['title']       = static::title;
        $info['printTime']   = $this->time;
        $info['stid']        = static::findStaff($info['stid']);
        $info['targetId']    = static::getCompanyName($info['targetId']);
        $info['qr']          = 'source=' . static::printPage . 'Other&id=' . $info['id'];
        $info['orderDate']   = date('Y/m/d', strtotime($info['time']));
        $detail              = find(['table' => static::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items               = [];
        $x                   = 1;
        $totalNum            = $totalMoney = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[]  = [
                'no'               => $x,
                'materialCode'     => $material['code'],
                'materialName'     => $material['name'],
                'warehouse'        => warehouseClass::getName($array['warehouseId']),
                'model'            => $material['model'],
                'unit'             => $array['unit'],
                'batch'            => $array['batch'],
                'num'              => static::lostZero($array['num'], 'numPrecision'),
                'packing_quantity' => static::lostZero($array['packing_quantity'], 'numPrecision'),
                'box_capacity'     => static::lostZero($array['box_capacity'], 'numPrecision'),
                'remainder'        => static::lostZero($array['remainder'], 'numPrecision'),
                'price'            => static::lostZero($array['price'], 'pricePrecision'),
                'money'            => static::formattingFigure($array['num'] * $array['price']),
            ];
            $x++;
            $totalNum   += floatval($array['num']);
            $totalMoney += static::formattingFigure($array['num'] * $array['price']);
        }
        $append         = [
            'no'    => L('outStockExec.printPage.total'),
            'num'   => static::lostZero($totalNum, 'numPrecision'),
            'money' => static::lostZero($totalMoney),
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(static::printPage, $info, '出库');
        } else {
            return $info;
        }
    }


    /**
     * 打印产品标识卡
     *
     * @return string
     */
    public function printCard(): string
    {
        $idArr = $this->get('body') ? explode(';', $this->get('body')) : [];
        $data  = [];
        foreach ($idArr as $id) {
            if (empty($id)) {
                continue;
            }
            $detail = find(['table' => self::tableMx, 'where' => "orderId = '$id' order by list asc"])['array'];
            foreach ($detail as $array) {
                $material               = query('material', "id = '$array[materialId]'");
                $inventory_detail       = query('inventory_detail', "id = '$array[sourceId]'");
                $sale_send_order_detail = query('sale_send_order_detail', "id = '$inventory_detail[sourceId]'");
                $data[]                 = [
                    'materialCode'     => $material['code'],
                    'materialName'     => $material['name'],
                    'khMaterialName'   => $sale_send_order_detail['khMaterialName'],
                    'khMaterialCode'   => $sale_send_order_detail['khMaterialCode'],
                    'model'            => $material['model'],
                    'batch'            => $array['batch'],
                    'packing_quantity' => self::lostZero($array['packing_quantity'], 'numPrecision'),
                    'box_capacity'     => self::lostZero($array['box_capacity'], 'numPrecision'),
                    'remainder'        => self::lostZero($array['remainder'], 'numPrecision'),
                    'num'              => self::lostZero($array['num'], 'numPrecision'),
                    'manufacturer'     => 'manufacturer',
                ];
            }
        }
        return (new printTemplateClass())->start(self::printPage, $data, '产品标识卡');
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'往来单位编号',
                    'aliasName'=>'往来单位编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'往来单位名称',
                    'aliasName'=>'往来单位名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据备注',
                    'aliasName'=>'单据备注',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'待出库单号',
                    'aliasName'=>'待出库单号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'仓库编码',
                    'aliasName'=>'仓库编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'库位编码',
                    'aliasName'=>'库位编码',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'库位名称',
                    'aliasName'=>'库位名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                    'isMust'=>true,
                ],
            ]
        };
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'出库完成时间',
                    'aliasName'=>'出库完成时间',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
                [
                    'columnName'=>'待出库单号',
                    'aliasName'=>'待出库单号',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'库位',
                    'aliasName'=>'库位',
                ],
                [
                    'columnName'=>'单据数量',
                    'aliasName'=>'单据数量',
                ],
                [
                    'columnName'=>'已出库数量',
                    'aliasName'=>'已出库数量',
                ],
                [
                    'columnName'=>'本次出库数量',
                    'aliasName'=>'本次出库数量',
                ],
                [
                    'columnName'=>'装箱数',
                    'aliasName'=>'装箱数',
                ],
                [
                    'columnName'=>'箱容数',
                    'aliasName'=>'箱容数',
                ],
                [
                    'columnName'=>'余数',
                    'aliasName'=>'余数',
                ],
                [
                    'columnName'=>'批号',
                    'aliasName'=>'批号',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',
                ],
                [
                    'columnName'=>'批次可用数量',
                    'aliasName'=>'批次可用数量',
                ],
            ]
        };
    }
}
